package com.hydong.novatest.activity

import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.view.*
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import androidx.fragment.app.FragmentContainerView
import com.hydong.novatest.R
import com.hydong.novatest.Utils.QDSkinManager
import com.hydong.novatest.base.BaseActivity
import com.hydong.novatest.fragment.ForumFragment
import com.hydong.novatest.fragment.HomeFragment
import com.hydong.novatest.fragment.MineFragment
import com.qmuiteam.qmui.arch.annotation.DefaultFirstFragment
import com.qmuiteam.qmui.arch.annotation.FirstFragments
import com.qmuiteam.qmui.arch.annotation.LatestVisitRecord
import com.qmuiteam.qmui.skin.QMUISkinHelper
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.skin.QMUISkinManager.OnSkinChangeListener
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.util.QMUIResHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.util.QMUIViewOffsetHelper
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.qmuiteam.qmui.widget.dialog.QMUIDialog.MenuDialogBuilder
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups
import java.util.*

@FirstFragments(value = [HomeFragment::class, ForumFragment::class, MineFragment::class])
@DefaultFirstFragment(ForumFragment::class)
@LatestVisitRecord
class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val skinManager = QMUISkinManager.defaultInstance(this)
        setSkinManager(skinManager)
        mOnSkinChangeListener.onSkinChange(skinManager, -1, skinManager.currentSkin)

//        val root: View = LayoutInflater.from(this).inflate(R.layout.activity_main, null)
//
//        var topbar: QMUITopBarLayout = root.findViewById(R.id.topbar)
//        topbar.addLeftBackImageButton().setOnClickListener(View.OnClickListener { popBackStack() })
//
//        setContentView(root)
    }

    override fun onCreateRootView(fragmentContainerId: Int): RootView? {
        return CustomRootView(this, fragmentContainerId)
    }

    internal class CustomRootView(context: Context?, fragmentContainerId: Int) : RootView(context, fragmentContainerId) {
        private var mGlobalAction: QMUIPopup? = null
        private val fragmentContainer: FragmentContainerView
        private val globalBtn: QMUIRadiusImageView2
        private val globalBtnOffsetHelper: QMUIViewOffsetHelper
        private val btnSize: Int
        private val touchSlop: Int
        private var touchDownX = 0f
        private var touchDownY = 0f
        private var lastTouchX = 0f
        private var lastTouchY = 0f
        private var isDragging = false
        private var isTouchDownInGlobalBtn = false
        override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
            super.onLayout(changed, left, top, right, bottom)
            globalBtnOffsetHelper.onViewLayout()
        }

        override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
            val x = event.x
            val y = event.y
            val action = event.action
            if (action == MotionEvent.ACTION_DOWN) {
                isTouchDownInGlobalBtn = isDownInGlobalBtn(x, y)
                lastTouchX = x
                touchDownX = lastTouchX
                lastTouchY = y
                touchDownY = lastTouchY
            } else if (action == MotionEvent.ACTION_MOVE) {
                if (!isDragging && isTouchDownInGlobalBtn) {
                    val dx = (x - touchDownX).toInt()
                    val dy = (y - touchDownY).toInt()
                    if (Math.sqrt(dx * dx + dy * dy.toDouble()) > touchSlop) {
                        isDragging = true
                    }
                }
                if (isDragging) {
                    var dx = (x - lastTouchX).toInt()
                    var dy = (y - lastTouchY).toInt()
                    val gx = globalBtn.left
                    val gy = globalBtn.top
                    val gw = globalBtn.width
                    val w = width
                    val gh = globalBtn.height
                    val h = height
                    if (gx + dx < 0) {
                        dx = -gx
                    } else if (gx + dx + gw > w) {
                        dx = w - gw - gx
                    }
                    if (gy + dy < 0) {
                        dy = -gy
                    } else if (gy + dy + gh > h) {
                        dy = h - gh - gy
                    }
                    globalBtnOffsetHelper.leftAndRightOffset = globalBtnOffsetHelper.leftAndRightOffset + dx
                    globalBtnOffsetHelper.topAndBottomOffset = globalBtnOffsetHelper.topAndBottomOffset + dy
                }
                lastTouchX = x
                lastTouchY = y
            } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
                isDragging = false
                isTouchDownInGlobalBtn = false
            }
            return isDragging
        }

        private fun isDownInGlobalBtn(x: Float, y: Float): Boolean {
            return globalBtn.left < x && globalBtn.right > x && globalBtn.top < y && globalBtn.bottom > y
        }

        override fun onTouchEvent(event: MotionEvent): Boolean {
            val x = event.x
            val y = event.y
            val action = event.action
            if (action == MotionEvent.ACTION_DOWN) {
                isTouchDownInGlobalBtn = isDownInGlobalBtn(x, y)
                lastTouchX = x
                touchDownX = lastTouchX
                lastTouchY = y
                touchDownY = lastTouchY
            } else if (action == MotionEvent.ACTION_MOVE) {
                if (!isDragging && isTouchDownInGlobalBtn) {
                    val dx = (x - touchDownX).toInt()
                    val dy = (y - touchDownY).toInt()
                    if (Math.sqrt(dx * dx + dy * dy.toDouble()) > touchSlop) {
                        isDragging = true
                    }
                }
                if (isDragging) {
                    var dx = (x - lastTouchX).toInt()
                    var dy = (y - lastTouchY).toInt()
                    val gx = globalBtn.left
                    val gy = globalBtn.top
                    val gw = globalBtn.width
                    val w = width
                    val gh = globalBtn.height
                    val h = height
                    if (gx + dx < 0) {
                        dx = -gx
                    } else if (gx + dx + gw > w) {
                        dx = w - gw - gx
                    }
                    if (gy + dy < 0) {
                        dy = -gy
                    } else if (gy + dy + gh > h) {
                        dy = h - gh - gy
                    }
                    globalBtnOffsetHelper.leftAndRightOffset = globalBtnOffsetHelper.leftAndRightOffset + dx
                    globalBtnOffsetHelper.topAndBottomOffset = globalBtnOffsetHelper.topAndBottomOffset + dy
                }
                lastTouchX = x
                lastTouchY = y
            } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
                isDragging = false
                isTouchDownInGlobalBtn = false
            }
            return isDragging || super.onTouchEvent(event)
        }

        override fun getFragmentContainerView(): FragmentContainerView {
            return fragmentContainer
        }

        init {
            btnSize = QMUIDisplayHelper.dp2px(context, 56)
            fragmentContainer = FragmentContainerView(context!!)
            fragmentContainer.id = fragmentContainerId
            addView(
                fragmentContainer, LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            globalBtn = QMUIRadiusImageView2(context)
            globalBtn.setImageResource(R.mipmap.icon_theme)
            globalBtn.scaleType = ImageView.ScaleType.CENTER_INSIDE
            globalBtn.setRadiusAndShadow(
                btnSize / 2,
                QMUIDisplayHelper.dp2px(getContext(), 16), 0.4f
            )
            globalBtn.borderWidth = 1
            globalBtn.borderColor = QMUIResHelper.getAttrColor(context, R.attr.qmui_skin_support_color_separator)
            globalBtn.setBackgroundColor(QMUIResHelper.getAttrColor(context, R.attr.app_skin_common_background))
            globalBtn.setOnClickListener { v -> showGlobalActionPopup(v) }

            val globalBtnLp = LayoutParams(btnSize, btnSize)
            globalBtnLp.gravity = Gravity.BOTTOM or Gravity.RIGHT
            globalBtnLp.bottomMargin = QMUIDisplayHelper.dp2px(context, 60)
            globalBtnLp.rightMargin = QMUIDisplayHelper.dp2px(context, 24)
            val builder = QMUISkinValueBuilder.acquire()
            builder.background(R.attr.app_skin_common_background)
            builder.border(R.attr.qmui_skin_support_color_separator)
            builder.tintColor(R.attr.app_skin_common_img_tint_color)
            QMUISkinHelper.setSkinValue(globalBtn, builder)
            builder.release()
            addView(globalBtn, globalBtnLp)
            globalBtnOffsetHelper = QMUIViewOffsetHelper(globalBtn)
            touchSlop = ViewConfiguration.get(context).scaledTouchSlop
        }

        private fun showGlobalActionPopup(v: View) {
            val listItems = arrayOf(
                "Change Skin",
                "Open SkinMaker(Developing)",
                "Export SkinMaker Result"
            )
            val data: MutableList<String> = ArrayList()
            Collections.addAll(data, *listItems)
            val adapter: ArrayAdapter<String> = ArrayAdapter<String>(context, R.layout.simple_list_item, data)
            val onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
                if (i == 0) {
                    val items = arrayOf("蓝色（默认）", "黑色", "白色")
                    MenuDialogBuilder(context)
                        .addItems(items) { dialog, which ->
                            QDSkinManager.changeSkin(which + 1)
                            dialog.dismiss()
                        }
                        .setSkinManager(QMUISkinManager.defaultInstance(context))
                        .create()
                        .show()
                } else if (i == 1) {
                    //
                } else if (i == 2) {
                    //
                }
                if (mGlobalAction != null) {
                    mGlobalAction?.dismiss()
                }
            }
            mGlobalAction = QMUIPopups.listPopup(
                context,
                QMUIDisplayHelper.dp2px(context, 250),
                QMUIDisplayHelper.dp2px(context, 300),
                adapter,
                onItemClickListener
            )
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                .shadow(true)
                .edgeProtection(QMUIDisplayHelper.dp2px(context, 10))
                .offsetYIfTop(QMUIDisplayHelper.dp2px(context, 5))
                .skinManager(QMUISkinManager.defaultInstance(context))
                .show(v)
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
    }

    override fun onStart() {
        super.onStart()
        skinManager?.addSkinChangeListener(mOnSkinChangeListener)
    }

    override fun onStop() {
        super.onStop()
        skinManager?.removeSkinChangeListener(mOnSkinChangeListener)
    }

    private val mOnSkinChangeListener = OnSkinChangeListener { skinManager, oldSkin, newSkin ->
        if (newSkin == QDSkinManager.SKIN_WHITE) {
            QMUIStatusBarHelper.setStatusBarLightMode(this@MainActivity)
        } else {
            QMUIStatusBarHelper.setStatusBarDarkMode(this@MainActivity)
        }
    }

}
